import { Injectable } from '@angular/core';
import { Member, SearchMember } from '../components/Interfaces/Member';
import { Http, Headers } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/toPromise';


const httpOptions = {
  headers: new Headers({
    'Content-Type': 'application/json',
  })
};

@Injectable()
export class MemberService {

    private apiUrl = '/api/v1/member';  // URL to web api
    constructor(
        private http: Http,
    ) { }
    getMembers(): Observable<any> {
        return this.http.get(this.apiUrl, httpOptions).map(res => res.json());
    }
    getMembersByCondition (condition: SearchMember): Observable<any> {
        let apiUrl = this.apiUrl;
        if ( condition.name ) {
            if (apiUrl.indexOf('?') !== -1) {
                apiUrl = apiUrl + '&name=' + condition.name;
            }
            if (apiUrl.indexOf('?') === -1) {
                apiUrl = apiUrl + '?name=' + condition.name;
            }
        }
        if ( condition.page ) {
            if (apiUrl.indexOf('?') !== -1) {
                apiUrl = apiUrl + '&page=' + condition.page;
            }
            if (apiUrl.indexOf('?') === -1) {
                apiUrl = apiUrl + '?page=' + condition.page;
            }
        }

        return this.http.get(apiUrl, httpOptions).map(res => res.json());
    }
    /**
     * 新增课程
     */
    addMember(member: Member): Observable<any> {
        this.resetApiUrl();
        return this.http.post(this.apiUrl, member, httpOptions).map(res => res.json());
    }

    editMember(member: Member): Observable<any> {
        return this.http.put(this.apiUrl + '/' + member.id, member, httpOptions).map(res => res.json());
    }

    resetApiUrl() {
        this.apiUrl = '/api/v1/member';
    }

    removeMember(member: Member): Observable<any> {
        return this.http.delete(this.apiUrl + '/' + member.id, httpOptions)
                .map(res => res.json());
    }


    /**
     *
     * @param id_list 根据id数组查寻
     */
    getMembersByIds(id_list: Array<any>) {
        return this.http.post(this.apiUrl + '/byids', id_list, httpOptions).map(res => res.json());
    }

}
